from .base import BaseForm
from app01 import models
import datetime
from django import forms
class DeployTaskModelForm(BaseForm):

    exclude_bootstrap = ['before_download_template','after_download_template','before_deploy_template','after_deploy_template']
    # before_download_select=forms.ChoiceField(required=False,label='下载前',choices=[[0,'请选择'],[1,'模板1']])
    before_download_select = forms.ChoiceField(required=False, label='下载前',)
    before_download_title=forms.CharField(required=False,label='模板名称')
    before_download_template=forms.BooleanField(required=False,widget=forms.CheckboxInput,label='是否存为模板')

    after_download_select = forms.ChoiceField(required=False, label='下载后')
    after_download_title = forms.CharField(required=False, label='模板名称')
    after_download_template = forms.BooleanField(required=False, widget=forms.CheckboxInput, label='是否存为模板')

    before_deploy_select = forms.ChoiceField(required=False, label='发布前')
    before_deploy_title = forms.CharField(required=False, label='模板名称')
    before_deploy_template = forms.BooleanField(required=False, widget=forms.CheckboxInput, label='是否存为模板')

    after_deploy_select = forms.ChoiceField(required=False, label='发布后')
    after_deploy_title = forms.CharField(required=False, label='模板名称')
    after_deploy_template = forms.BooleanField(required=False, widget=forms.CheckboxInput, label='是否存为模板')

    class Meta:
        model=models.DeployTask
        fields='__all__'
        exclude=['uid','status','project']

    def __init__(self,project,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.project=project
        self.init_hook()

    def save(self, commit=True):
        '''
        重写save方法
        :param commit:
        :return:
        '''
        self.instance.uid=self.create_uid()
        self.instance.project_id=self.project.id
        super().save(commit)
        #保存钩子模板
        if self.cleaned_data.get('before_download_template'):
            #下载前脚本
            title=self.cleaned_data.get('before_download_title')
            content=self.cleaned_data.get('before_download_script')
            try:
                models.HookTemplate.objects.create(title=title,content=content,hook=2)
            except Exception as e:
                self.add_error('before_download_title', '模板创建失败')
        if self.cleaned_data.get('after_download_template'):
            #下载后脚本
            title=self.cleaned_data.get('after_download_title')
            content=self.cleaned_data.get('after_download_script')
            try:
                models.HookTemplate.objects.create(title=title,content=content,hook=4)
            except Exception as e:
                self.add_error('after_download_title', '模板创建失败')
        if self.cleaned_data.get('before_deploy_template'):
            #发布前脚本
            title=self.cleaned_data.get('before_deploy_title')
            content=self.cleaned_data.get('before_deploy_script')
            try:
                models.HookTemplate.objects.create(title=title,content=content,hook=6)
            except Exception as e:
                self.add_error('before_deploy_title', '模板创建失败')
        if self.cleaned_data.get('after_deploy_template'):
            title=self.cleaned_data.get('after_deploy_title')
            content=self.cleaned_data.get('after_deploy_script')
            try:
                models.HookTemplate.objects.create(title=title,content=content,hook=8)
            except Exception as e:
                self.add_error('after_deploy_title', '模板创建失败')
    def create_uid(self):
        '''
        生成uid
        :return:
        '''
        title=self.project.title
        env=self.project.env
        tag=self.cleaned_data.get('tag')
        datestr=datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        return '{}-{}-{}-{}'.format(title,tag,env,datestr)

    def init_hook(self):
        '''
        初始化话钩子函数的选择脚本
        :return:
        '''
        #下载前脚本
        before_download_select_choices=[(0,'请选择'),]
        bdq_=models.HookTemplate.objects.filter(hook=2).values_list('id','title')
        before_download_select_choices.extend(bdq_)
        #下载后脚本
        after_download_select_choices = [(0, '请选择'), ]
        adq_=models.HookTemplate.objects.filter(hook=4).values_list('id','title')
        after_download_select_choices.extend(adq_)
        #发布前脚本
        before_deploy_select_choices = [(0, '请选择'), ]
        bdpq_ = models.HookTemplate.objects.filter(hook=6).values_list('id', 'title')
        before_deploy_select_choices.extend(bdpq_)
        #发布后脚本
        after_deploy_select_choices = [(0, '请选择'), ]
        adpq_ = models.HookTemplate.objects.filter(hook=8).values_list('id', 'title')
        after_deploy_select_choices.extend(adpq_)
        self.fields['before_download_select'].choices=before_download_select_choices
        self.fields['after_download_select'].choices=after_download_select_choices
        self.fields['before_deploy_select'].choices=before_deploy_select_choices
        self.fields['after_deploy_select'].choices=after_deploy_select_choices

    def clean(self):
        if self.cleaned_data.get('before_download_template'):
            if not self.cleaned_data.get('before_download_title'):
                self.add_error('before_download_title','模板名不能为空')

        if self.cleaned_data.get('after_download_template'):
            if not self.cleaned_data.get('after_download_title'):
                self.add_error('after_download_title','模板名不能为空')

        if self.cleaned_data.get('before_deploy_template'):
            if not self.cleaned_data.get('before_deploy_title'):
                self.add_error('before_deploy_title','模板名不能为空')

        if self.cleaned_data.get('after_deploy_template'):
            if not self.cleaned_data.get('after_deploy_title'):
                self.add_error('after_deploy_title','模板名不能为空')
        return self.cleaned_data